package com.yangzihao.gateway;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(-1)   //@Order 表示该过滤器的顺序 或者顺便实现order接口可以
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //获取auth参数值
        String auth = queryParams.getFirst("auth");
        //判断值是否等于admin
        if("admin".equals(auth)){
            //放行
            return chain.filter(exchange);
        }
        //  否 拦截
        // 为了让用户有更友好的体验 设置响应状态码404 HttpStatus.UNAUTHORIZED表示未登录(这是个枚举型)
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        //拦截请求
        return exchange.getResponse().setComplete();//意思就是响应已完成
    }
}
